<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-position="top"

    >
      <el-form-item label="链接id" prop="linkId">
        <el-input
          v-model="queryParams.linkId"
          placeholder="请输入链接id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="款式编码" prop="iId">
        <el-input
          v-model="queryParams.iId"
          placeholder="请输入款式编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="链接名称" prop="linkName">
        <el-input
          v-model="queryParams.linkName"
          placeholder="请输入链接名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="链接归属人" prop="userId">
        <CascaderUser v-model="queryParams.userId"
                      class="!w-240px"
                      v-if="checkPermi(['operation:price-link:admin'])"
        />

        <el-select v-else v-model="queryParams.userId" placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in userAuthList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="店铺" prop="shopId">
        <select-basic-shop v-model="queryParams.shopId" class="!w-240px"/>

      </el-form-item>

      <!--      <el-form-item label="创建人" prop="creator">-->
      <!--        <CascaderUser v-model="queryParams.creator"/>-->
      <!--      </el-form-item>-->


      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="操作">
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>


      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-button
      type="primary"
      plain
      @click="handleJDAdd"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      京东链接定价
    </el-button>
    <el-button
      type="success"
      plain
      @click="handleAuthManage"
    >
      <Icon icon="ep:setting" class="mr-5px"/>
      权限维护
    </el-button>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column label="链接id" align="center" prop="linkId" width="160"/>
      <el-table-column label="款式编码" align="center" prop="iId" width="120"/>
      <el-table-column label="链接名称" align="center" prop="linkName" width="200"/>
      <el-table-column label="链接归属人" align="center" prop="userName" width="100"/>
      <el-table-column label="店铺" align="center" prop="shopName" width="200"/>
      <el-table-column label="销售额" align="center" prop="sales" width="100"/>
      <el-table-column label="利润" align="center" prop="profit" width="100"/>
      <el-table-column label="平台" align="center" prop="platform" width="100"/>
      <el-table-column v-if="fixedName1" :label="fixedName1" align="center" prop="fixedValue1"/>
      <el-table-column v-if="fixedName2" :label="fixedName2" align="center" prop="fixedValue2"/>
      <el-table-column v-if="fixedName3" :label="fixedName3" align="center" prop="fixedValue3"/>
      <el-table-column :label="rateName1" align="center" prop="rateValue1"/>
      <el-table-column :label="rateName2" align="center" prop="rateValue2"/>
      <el-table-column :label="rateName3" align="center" prop="rateValue3"/>
      <el-table-column :label="discountName" align="center" prop="discount"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleCalculate(scope.row)"
          >
            计算
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PriceLinkForm ref="formRef" @success="getList"/>
  <PriceCalculate ref="priceCalculateRef" @success="getList"/>
  <PriceJDCalculate ref="priceJDCalculateRef" @success="getList"/>
  <PriceAuthForm ref="priceAuthFormRef"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import {PriceLink, PriceLinkApi} from '@/api/business/operation/price/link'
import PriceLinkForm from './PriceLinkForm.vue'
import PriceCalculate from "@/views/business/operation/price/componets/PriceCalculate.vue";
import PriceJDCalculate from "@/views/business/operation/price/componets/PriceJDCalculate.vue";
import PriceAuthForm from './PriceAuthForm.vue'
import {PriceConfigApi} from "@/api/business/operation/price/config";
import {checkPermi} from '@/utils/permission'
import {useUserStore} from "@/store/modules/user";
import {getVisibleUserIds} from "@/api/business/operation/price/auth";

/** 商品定价-链接 列表(京东) */
defineOptions({name: 'OperationPriceLinkJD'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化
const userStore = useUserStore()

const loading = ref(true) // 列表的加载中
const list = ref<PriceLink[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  linkId: undefined,
  iId: undefined,
  linkName: undefined,
  userId: undefined,
  shopId: undefined,
  sales: undefined,
  profit: undefined,
  platform: undefined,
  fixedValue1: undefined,
  fixedValue2: undefined,
  fixedValue3: undefined,
  rateValue1: undefined,
  rateValue2: undefined,
  rateValue3: undefined,
  discount: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const fixedName1 = ref('')
const fixedName2 = ref('')
const fixedName3 = ref('')
const rateName1 = ref('')
const rateName2 = ref('')
const rateName3 = ref('')
const discountName = ref('')

/**
 * 获取配置参数
 */
const getConfig = async () => {
  let queryParams = {
    pageNo: 1,
    pageSize: 1000,
    configKey: '京东'
  }
  const data = await PriceConfigApi.getPriceConfigPage(queryParams)

  // 查找 configKey 为"京东"的配置
  if (data.list && data.list.length > 0) {
    const jdConfig = data.list.find(item => item.configKey === '京东')
    if (jdConfig && jdConfig.configValue) {
      try {
        // 解析 JSON 字符串
        const configData = JSON.parse(jdConfig.configValue)

        // 设置名称（只设置名称用于表头显示）
        rateName1.value = configData.rateName1 || ''
        rateName2.value = configData.rateName2 || ''
        rateName3.value = configData.rateName3 || ''
        fixedName1.value = configData.fixedName1 || ''
        fixedName2.value = configData.fixedName2 || ''
        fixedName3.value = configData.fixedName3 || ''
        discountName.value = '折扣'
      } catch (error) {
        console.error('解析配置失败:', error)
        message.error('配置格式错误')
      }
    }
  }
}

/** 查询列表 */
const getList = async () => {
  // 验证 userId 是否为空
  if (!queryParams.userId) {
    message.warning('请选择链接归属人')
    return
  }

  loading.value = true
  try {
    const data = await PriceLinkApi.getPriceLinkPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.userId = userStore.user.id
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PriceLinkApi.deletePriceLink(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

const priceCalculateRef = ref()

const handleAdd = async () => {
  priceCalculateRef.value.open()
}

const priceJDCalculateRef = ref()
const handleJDAdd = async () => {
  priceJDCalculateRef.value.open()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    exportLoading.value = true
    await PriceLinkApi.exportPriceLink(queryParams)
    message.success(t('common.exportSuccess'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 计算按钮操作 */
const handleCalculate = async (row: PriceLink) => {
  priceJDCalculateRef.value.open(row)
}

/** 权限维护按钮操作 */
const priceAuthFormRef = ref()
const handleAuthManage = () => {
  priceAuthFormRef.value.open()
}

const userAuthList = ref([])
const getAuthUserList = async () => {
  const data = await getVisibleUserIds()
  userAuthList.value = data
}

/** 初始化 **/
onMounted(() => {
  queryParams.userId = userStore.user.id.toString()
  getList()
  getConfig()
  getAuthUserList()
})
</script>
